package com.flot.yazb.home.moudle.pay;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.flot.yazb.R;
import com.flot.yazb.base.BActivity;
import com.flot.yazb.base.BApplication;
import com.flot.yazb.base.BDialog;
import com.flot.yazb.SPKeyConfig;
import com.flot.yazb.base.model.BModel;
import com.flot.yazb.aop.stub.CodeStub;
import com.flot.yazb.model.PayModel;
import com.flot.yazb.model.user.UserModel;
import com.flot.yazb.widget.utils.IsNullOrEmpty;
import com.flot.yazb.widget.utils.PlatsOpenUtil;
import com.flot.yazb.widget.utils.ResourcesUtils;
import com.flot.yazb.widget.utils.ScreenUtil;
import com.flot.yazb.widget.utils.SharedPreferencesUtils;
import com.flot.yazb.widget.utils.ToastUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;


public class WebViewActivity extends BActivity {
    private static final String KEY_URL = "url";
    private WebView webView;
    private static ProgressBar progressBar;
    private UserModel userModel = BApplication.getInstance().getUserModel();
    private String pay_type;
    private String money;
    private String param;
    private Button open;
    private String pay_link;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initWebView();

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new exiteDialog(WebViewActivity.this).show();
            }
        });

        open = (Button) findViewById(R.id.open);
        open.setClickable(false);
        open.setEnabled(false);
        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScreenUtil.GetandSaveCurrentImage(WebViewActivity.this);
                ToastUtil.showToast(activity,"二维码保存成功，正在跳转微信客户端。");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        boolean b = PlatsOpenUtil.isWeixinAvilible(WebViewActivity.this);
                        if (b) {
                            PlatsOpenUtil.goWx(WebViewActivity.this);
                        } else {
                            ToastUtil.showToast(activity, "您还没有安装微信");
                        }
                    }
                },3000);

            }
        });

        int color = ResourcesUtils.getColor(this, R.color.colorPrimary);
        progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);

        pay_type = getIntent().getStringExtra("pay_type");
        money = getIntent().getStringExtra("money");
        param = getIntent().getStringExtra("param");
        pay_link = getIntent().getStringExtra("link");
        webView.loadUrl(pay_link);

    }

    /**
     * 解析网页，获取二维码地址
     */
    private void ParserXml(String link) {

        try {
            //还是一样先从一个URL加载一个Document对象。
            Document doc = Jsoup.connect(link).ignoreContentType(true).get();

            //“椒麻鸡”和它对应的图片都在<div class="pic">中
//            Elements titleAndPic = doc.select("div.pic");
            //使用Element.select(String selector)查找元素，使用Node.attr(String key)方法取得一个属性的值
//            Log.i("mytag", "title:" + titleAndPic.get(1).select("a").attr("title") + "pic:" + titleAndPic.get(1).select("a").select("img").attr("data-src"));

            //所需链接在<div class="detail">中的<a>标签里面
//            Elements url = doc.select("div.detail").select("a");
//            Log.i("mytag", "url:" + url.get(i).attr("href"));

            //原料在<p class="subcontent">中
//            Elements burden = doc.select("p.subcontent");
            //对于一个元素中的文本，可以使用Element.text()方法
//            Log.i("mytag", "burden:" + burden.get(1).text());

            Elements burden = doc.select("img");
            Log.i("mytag", "burden:" + burden.attr("src"));

        } catch (Exception e) {
            Log.i("mytag", e.toString());
        }
    }

    /**
     * 获取支付链接
     */
    private void getPayLink() {

        PayModel.getLink(pay_type, userModel.id, money, param, new BModel.Transit<PayModel>(this) {
            @Override
            public void onBorn(final PayModel serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
                    if (serializable != null && serializable.pay_link != null)
                        webView.loadUrl(serializable.pay_link);
                    if (IsNullOrEmpty.isEmpty(serializable.mode)) {
                        open.setVisibility(View.GONE);
                    } else {
                        open.setVisibility(View.VISIBLE);
                    }

                } else {
                    ToastUtil.showToast(activity, message);
                }
            }
        });
    }

    private void initWebView() {
        webView = (WebView) findViewById(R.id.webview);
        WebSettings settings = webView.getSettings();
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);

        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
        settings.setLoadWithOverviewMode(true);

        settings.setGeolocationEnabled(true);
        settings.setDefaultFixedFontSize(16); // v3.3 不设默认字体大小，当手机设置极小字体时候，部分H5页面显示不正常
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setBlockNetworkImage(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setSaveFormData(false);
        settings.setLoadsImagesAutomatically(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDatabaseEnabled(true);

        String user_agent =
                "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1";
        settings.setUserAgentString(user_agent);
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }

        webView.setWebChromeClient(new SimpleChromeClient(this));
        webView.setWebViewClient(new mWebViewClient());

        settings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JsCallJava(), "jsObj");

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        new exiteDialog(this).show();
        return true;
    }

    /**
     * js调用java方法获取值
     */
    private class JsCallJava {

        @JavascriptInterface
        public String getTitle(String name) {

            return "";
        }
    }

    public class SimpleChromeClient extends WebChromeClient {
        protected Activity mActivity;

        public SimpleChromeClient(Activity activity) {
            mActivity = activity;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress != 100) {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);
            } else {
                ScreenUtil.GetandSaveCurrentImage(WebViewActivity.this);
                progressBar.setVisibility(View.GONE);
                open.setClickable(true);
                open.setEnabled(true);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (consoleMessage != null) {
                String jsMessage = consoleMessage.message();
                if (!TextUtils.isEmpty(jsMessage)) {
                    Log.d("js_info", jsMessage);
                }
            }

            return super.onConsoleMessage(consoleMessage);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            DialogInterface.OnClickListener dialogButtonOnClickListener = new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int clickedButton) {
                    if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
                        callback.invoke(origin, true, true);
                    } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
                        callback.invoke(origin, false, false);
                    }
                }
            };

            new AlertDialog.Builder(mActivity)
                    .setMessage("是否允许获取您的位置信息?")
                    .setPositiveButton("允许", dialogButtonOnClickListener)
                    .setNegativeButton("拒绝", dialogButtonOnClickListener)
                    .show();
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
    }


    public static class mWebViewClient extends WebViewClient {

        public mWebViewClient() {
            super();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }
    }

    /**
     * 退出充值dialog
     */
    class exiteDialog extends BDialog implements View.OnClickListener {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.dialog_exit_pay);
            TextView cancle = (TextView) findViewById(R.id.cancle);
            TextView ok = (TextView) findViewById(R.id.ok);
            cancle.setOnClickListener(this);
            ok.setOnClickListener(this);
        }

        public exiteDialog(Context context) {
            super(context);
        }

        @Override
        public boolean isCancelable(boolean b) {
            return true;
        }

        @Override
        public int setGravity(int gravity) {
            return 0;
        }

        @Override
        public int setPadWidth(float width) {
            return 0;
        }

        @Override
        public int setPadHeight(float height) {
            return 0;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.cancle:
                    regetUserMsg();
                    dismiss();
                    break;
                case R.id.ok:
                    regetUserMsg();
                    dismiss();
                    break;
            }
        }
    }

    /**
     * 支付完成后获取用户信息
     */
    private void regetUserMsg() {
        showProgress();
        String id = SharedPreferencesUtils.getString(this, SPKeyConfig.USERID, "");
        UserModel.getUserMsg(id, new BModel.Transit<UserModel>(this) {
            @Override
            public void onBorn(UserModel serializable, String code, String message) {
                dismissProgress();
                if (code.equals(CodeStub.B_OK)) {
                    BApplication.getInstance().setUserModel(serializable);
                    SharedPreferencesUtils.saveString(activity, SPKeyConfig.USERID, serializable.id);
                    finish();
                } else {
                    ToastUtil.showToast(activity, message);
                }
            }
        });
    }
}
